import { PrismaAdapter } from "@auth/prisma-adapter";
import { type DefaultSession, type NextAuthConfig } from "next-auth";
import GitHubProvider from "next-auth/providers/github";
import CredentialsProviders from "next-auth/providers/credentials";
import bcrypt from "bcryptjs";

import { db } from "@/server/db";
import { LoginSchema } from "@/schemas";

/**
 * Module augmentation for `next-auth` types. Allows us to add custom properties to the `session`
 * object and keep type safety.
 *
 * @see https://next-auth.js.org/getting-started/typescript#module-augmentation
 */
declare module "next-auth" {
  interface Session extends DefaultSession {
    user: {
      id: string;
      // ...other properties
      // role: UserRole;
    } & DefaultSession["user"];
  }

  // interface User {
  //   // ...other properties
  //   // role: UserRole;
  // }
}

/**
 * Options for NextAuth.js used to configure adapters, providers, callbacks, etc.
 *
 * @see https://next-auth.js.org/configuration/options
 */
export const authConfig = {
  providers: [
    GitHubProvider,
    // 密码登录
    CredentialsProviders({
      name: "密码登录",
      credentials: {
        email: {
          label: "邮箱",
        },
        password: {
          label: "密码",
          type: "password",
        },
      },
      async authorize(credentials, request) {
        const { success, data } = LoginSchema.safeParse(credentials);
        if (success) {
          const { email, password } = data;
          const user = await db.user.findFirst({
            where: {
              email,
            },
          });

          if (!user?.password) return null;

          const isMatch = await bcrypt.compare(password, user.password as string);

          if (isMatch) {
            return {
              ...user,
              id: user.id,
            };
          }
        }
        return null;
      },
    }),
    // DiscordProvider,
    /**
     * ...add more providers here.
     *
     * Most other providers require a bit more work than the Discord provider. For example, the
     * GitHub provider requires you to add the `refresh_token_expires_in` field to the Account
     * model. Refer to the NextAuth.js docs for the provider you want to use. Example:
     *
     * @see https://next-auth.js.org/providers/github
     */
  ],
  adapter: PrismaAdapter(db),
  callbacks: {
    async jwt({ token, user }) {
      console.log("jwt", token, user);

      if (user) {
        token.id = user.id;
        token.phone = user.email;
      }
      return token;
    },
    session: ({ session, user }) => {
      console.log("session", session, user);

      return {
        ...session,
        user: {
          ...session.user,
          id: user.id,
        },
      };
    },
  },
  pages: {
    signIn: "/signIn",
    error: "/error",
  },
  secret: process.env.AUTH_SECRET,
} satisfies NextAuthConfig;
